<?php
include_once('./db.conf');
session_start();
$loggedIn=false;
// Connects to your Database 
$connection=mysqli_connect(DBHOST, DBUSER, DBPASS,DBDBNAME); 

if(isset($_COOKIE['CompanyCookie'])){
	$_SESSION['comID']=$_COOKIE['CompanyCookie'];
	$loggedIn=true;
	header("Location: index.php");
}

//if the login form is submitted

if (!$loggedIn && isset($_POST['submit'])) { // if form has been submitted


// makes sure they filled it in

	if(!$_POST['pass'] | !$_POST['id']) {
		die('You did not fill in a required field.');
	}
	//$_POST['pass'] = md5($_POST['pass']);
	// checks it against the database
	$query = "call getCompany($_POST[id])";
	if(!$check = mysqli_query($connection,$query))
		die ('Company ID Has To Be Numeric or Something Went Wrong Please Try Again...');
	else{
		$row= mysqli_fetch_assoc($check);
		if(strcmp($row['companyId'],$_POST['id']))
			die ('Wrong Company ID');
		else if(!strcmp($row['passwd'],$_POST['pass'])){
			$id=$row['companyId'];
			$hour=time()+300;//expires 5 minutes later
			$_SESSION['comID']=$row['companyId'];
			setcookie('CompanyCookie',$id,$hour);
			header("Location: index.php");
		}
		else
			die('Wrong Password');
	}
}
 else {	

// if they are not logged in
?>

<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
<table border="0">
<tr><td colspan=2><h1>Login</h1></td></tr>
<A HREF="registercomp.php">If You Do Not Have An Account, Click Here To Register</A><br><br>
<tr><td>ID:</td><td>
<input type="text" name="id" maxlength="40">
</td></tr>
<tr><td>Password:</td><td>
<input type="password" name="pass" maxlength="50">
</td></tr>
<tr><td colspan="2" align="right">
<input type="submit" name="submit" value="Login">
</td></tr>
</table>
</form>
<?php
}
mysqli_close($connection);
?>